
/*编辑器元素*/
var offsetTopOfScreen=0;
var offsetlefOfScreen=0;
var firstMouseMove=0;
$(document).ready(function(){



	var canvas1 = $('#layer1')[0];
    var ctx1 = canvas1.getContext('2d');
    var canvas2 = $('#layer2')[0];
    var ctx2 = canvas2.getContext('2d');

    var cellSize = 25;
    var cellSpacing = 10;
    var gridRows = 10;
    var gridCols = 10;
    
    // 绘制网格
    function drawGrid(context, rows, cols, cellSize, cellSpacing) {
        context.clearRect(0, 0, context.canvas.width, context.canvas.height);
        context.beginPath();
        for (var r = 0; r < rows; r++) {
            for (var c = 0; c < cols; c++) {
                var x = c * (cellSize + cellSpacing);
                var y = r * (cellSize + cellSpacing);
                context.rect(x, y, cellSize, cellSize);
            }
        }
        context.strokeStyle = 'black';
        context.stroke();
        context.closePath();
    }

    // 绘制选中的方格
    function highlightCells(context, mouseX, mouseY, rows, cols, cellSize, cellSpacing) {
        var rect = context.canvas.getBoundingClientRect();
        var offsetX = mouseX - rect.left;
        var offsetY = mouseY - rect.top;
        var selectedRow = Math.floor(offsetY / (cellSize + cellSpacing));
        var selectedCol = Math.floor(offsetX / (cellSize + cellSpacing));
        
        drawGrid(context, rows, cols, cellSize, cellSpacing);

        for (var r = 0; r <= selectedRow && r < rows; r++) {
            for (var c = 0; c <= selectedCol && c < cols; c++) {
                var x = c * (cellSize + cellSpacing);
                var y = r * (cellSize + cellSpacing);
                context.fillStyle = 'lightblue';
                context.fillRect(x, y, cellSize, cellSize);
            }
        }

        return {selectedRow, selectedCol}; // 返回选中的行和列
    }

    drawGrid(ctx1, gridRows, gridCols, cellSize, cellSpacing);

    $('#layer1').on('mousemove', function(e) {
        highlightCells(ctx1, e.clientX, e.clientY, gridRows, gridCols, cellSize, cellSpacing);
    });

    $('#layer1').on('click', function(e) {
        var selection = highlightCells(ctx1, e.clientX, e.clientY, gridRows, gridCols, cellSize, cellSpacing);
        alert('Selected grid - Rows: ' + (selection.selectedRow + 1) + ', Columns: ' + (selection.selectedCol + 1));
    });

    $('#toggleLayer1').click(function() {
        $('#layer1').toggle();
    });

    $('#toggleLayer2').click(function() {
        $('#layer2').toggle();
    });



 $(document).bind("contextmenu",function(e){ 
        return false; 
    }); 
	var cc = document.getElementById("canvas");
	//获取画板与页面的左上角边距
	offsetTopOfScreen=cc.getBoundingClientRect().top;
	offsetlefOfScreen=cc.getBoundingClientRect().left;
	var ctx = cc.getContext("2d");
	
	var a = new $.ButtonElement({x:0,y:0,w:200,h:100,Name:"第一个按钮",id:1,type:1});

	var b = new $.ButtonElement({x:30,y:170,w:150,h:150,Name:"第二个按钮",id:2,type:1});
	var c = new $.ButtonElement({x:30,y:400,w:150,h:150,Name:"第三个按钮",id:3,type:1});
	//var d = new $.ButtonElement({x:30,y:600,w:150,h:150,Name:"第四个按钮",id:4,type:1});
	


    //计算出光标与元件的左上角的相对位置 offsetX offsetY; offsetX=obj.x-point.x;offsetY=obj.y-point.y
    var offsetX=0;
	var offsetY=0;
	var hadSelectElement=0;//当前有没有选中元素
	var isMoving=0;
	var lastRet=-1;//在移动过程中，不在检查动作内容
	var selectItem=-1;  
	var visualSelectElement=-1;//视觉选择， 
 		//获取当前画板的原点
	ctx.translate(0,-offsetTopOfScreen);

	
	var PageElement= new Array();
	PageElement.push(a);
	PageElement.push(b);
	PageElement.push(c);
	//PageElement.push(d);
	
	
	$.each(PageElement, function (index, item) //绘制所有对像
	{               																								
	item.SetDc(ctx);
	item.DrawButton(0);		
																									
               
	});
	
	obj=$("#canvas");
	

	
	var drag=function(obj){
            
	obj.bind("mousedown",start);
	var LbuttonDown=0;
	//movemove事件必须绑定到$(document)上，鼠标移动是在整个屏幕上的
	 $(document).bind("mousemove",move);
	//此处的$(document)可以改为obj
	 $(document).bind("mouseup",stop);
	function start(event){
		
		        var ret;
													
				if(event.button==0){//判断是否点击鼠标左键
									 /*event.button=0|1|2 哪个事件被点击？ 0 	规定鼠标左键。1 	规定鼠标中键 2 	规定鼠标右键。
									  * clientX和clientY代表鼠标当前的横纵坐标
									  * offset()该方法返回的对象包含两个整型属性：top 和 left，以像素计。此方法只对可见元素有效。
									  * bind()绑定事件，同样unbind解绑定，此效果的实现最后必须要解绑定，否则鼠标松开后拖拽效果依然存在
									  * getX获取当前鼠标横坐标和对象离屏幕左侧距离之差（也就是left）值，
									  * getY和getX同样道理，这两个差值就是鼠标相对于对象的定位，因为拖拽后鼠标和拖拽对象的相对位置是不变的
									  */
									  LbuttonDown=1;
									  //点击下去要计算一下有没有在有效区域内？
									  //ret=a.Hits({x:event.clientX,y:event.clientY});
									  $.each(PageElement, function (index, item) {
               												//console.log(index + " X:" + item.x+" y:"+ item.y+" w:"+item.w+" h:"+item.h+" n:"+item.Name);
                										ret=item.Hits({x:event.clientX,y:event.clientY});
														selectItem=item.id;
														visualSelectElement=item.id;
														if(ret>=0)
														{
															 offsetX=item.GetLeft()-event.clientX;
										  					 offsetY=item.GetTop()-event.clientY;
										  					 hadSelectElement=1;  //标识选中了一个元素
															return false;
														}
																
               
															});
									  if(ret>=0)
									  {
										 
									  }
									  else
									  { 
									  	   hadSelectElement=0;  //取消选中元素标识
										   visualSelectElement=0;
									  }
									  
									  
									  
									  /*
									  右键放下时，选中元素对像，（点下时，调用判断有没有对像被选中）
									  */
                       
								}//end if(event.button==0){//判断是否点击鼠标左键
	
								if(event.button==2)
								{
									//alert(event.clientX);
									var x=event.clientX;
									var y=event.clientY;
									// 	    ctx.setLineDash([0, 0]);  //画虚线
									// 		ctx.beginPath();  
									// 		ctx.lineWidth = 1;
									// 		ctx.strokeStyle = '#000000';
									// 		ctx.moveTo(x,0);
									// 		ctx.lineTo(x,10);
									 //		ctx.fillText("开始",x+3,y,32);
									// 		ctx.stroke();	
									var ctx = cc.getContext("2d");
										 // var img=new Image()
										 // img.src="https://img-blog.csdnimg.cn/20201014180756916.png?x-oss-process=image/resize,m_fixed,h_64,w_64";
										 // img.onload = function () //确保图片已经加载完毕
										 // {
										 //     ctx.drawImage(img,x,y-offsetTopOfScreen);
										 // }
									

									return false ;
								}
								return false;//阻止默认事件或冒泡
						}// End function start(event)
               
			             
						function move(event){

													if(isMoving<=0&&LbuttonDown==0)
													{
														
														$.each(PageElement, function (index, item) {
               											ret=item.Hits({x:event.clientX,y:event.clientY});
														selectItem=item.id;
														lastRet=ret;
														if(ret>=0)
														{
															return false;
														}
																
               
															});
													
													}
													else
													{
														ret=lastRet;
													}
													if(ret>=0)
													{
													
													firstMouseMove=1;
													$.each(PageElement, function (index, item) {
               											
														if(selectItem==item.id)
														{
															isMoving=item.Moving({x:event.clientX,y:event.clientY,action:ret,hadSelectElement:hadSelectElement,offsetx:offsetX,offsety:offsetY});
															
															return false;
														}
																
               
													});
													Clean();
													$.each(PageElement, function (index, item) {   
													   // item.SetSelected(selectItem);            																								
														item.DrawButton(visualSelectElement);																											
               
													});
													
													
													}
													console.log(ret);
													console.log("selectItem:"+selectItem+" LbuttonDown:"+LbuttonDown+" isMoving:"+isMoving+" ret:"+ret+" px:"+event.clientX+" py:"+event.clientY +"  x:"+a.GetLeft()+" y:"+a.GetTop()+" r:"+a.GetRight()+" b:"+a.GetBottom());
													/*A:在移动过程中，如果有对像被选中，这里要更新图像的位置*/
													/*B:在移动过程中，如果在对像9个特征位置，显示不同的光标型状*/
													return false;//阻止默认事件或冒泡
											}//end function move(event)


						 function stop(event){
							//解绑定，这一步很必要，前面有解释
						   LbuttonDown=0;
						   isMoving=0;
						   hadSelectElement=0;  //取消选中元素标识
						   lastRet=-1;
						 //$(document).unbind("mousemove",move);
						 //$(document).unbind("mouseup",stop);
											
						 }//end  function stop
 			}//var drag=function(obj)		
   
    drag(obj);//传入的必须是jQuery对象，否则不能调用jQuery的自定义函数

function Clean(){
			var c = $("#canvas");//清场活动
			var width = c.attr('width'); 
			var height=c.attr('height');
			c.attr('width',0);    
			c.attr('width',width);    
    	    ctx.clearRect(0,0,1024,768); 
			
			
			
			
			
			//画竖线
			for( var i=0;i<width/25;i++)
			{	
				
				//画刻度
				if(!(i*25%100))
				{   ctx.setLineDash([0, 0]);  //画虚线
					ctx.beginPath();  
					ctx.lineWidth = 1;
					ctx.strokeStyle = '#000000';
					ctx.moveTo(i*25,0);
					ctx.lineTo(i*25,10);
					ctx.fillText(i*25,i*25+3,12,32);
					ctx.stroke();
				}
				if((i*25)%200)
				{
					ctx.beginPath();
					ctx.lineWidth = 0.5;
					ctx.strokeStyle = '#aaaaff';
					ctx.setLineDash([1, 1]);  //画虚线
					ctx.moveTo(i*25,0);
					ctx.lineTo(i*25,height);
					ctx.stroke();
					ctx.textAlign="left";
				}
				
			}
			//画横线
			for(var j=0;j<height/25;j++)
			{
				
				
				//画刻度
				if(!(j*25%100))
				{   ctx.setLineDash([0, 0]);  //画虚线
					ctx.beginPath();  
					ctx.lineWidth = 1;
					ctx.strokeStyle = '#000000';
					ctx.moveTo(0,j*25);
					ctx.lineTo(10,j*25);
					ctx.fillText(j*25,3,j*25-5,32);
					ctx.stroke();
				}
				if((j*25%200))
				{
					ctx.beginPath();
					ctx.lineWidth = 0.5;
					ctx.strokeStyle = '#aaaaff';
					ctx.setLineDash([1, 1]);  //画虚线
					ctx.moveTo(0,25*j);
					ctx.lineTo(width,25*j);
					ctx.stroke();
					ctx.textAlign="left";
					
				}
				
			}
			ctx.stroke();
			//画200大刻度线
			ctx.strokeStyle = '#797979';
			ctx.beginPath();  
			ctx.lineWidth = 1;
			ctx.setLineDash([6, 6]);  //画虚线
			for( var k=0;k<width/200;k++)//画坚线
			{
				ctx.moveTo(k*200,10);
				ctx.lineTo(k*200,height);
			}
			for(var j=0;j<height/200;j++)//画横线
			{
				ctx.moveTo(10,200*j);
				ctx.lineTo(width,200*j);
			}
		    ctx.stroke();
			
			
		
			
		};

});
 	

	
(function ($) {

    $.ButtonElement = function (arg) {

        var name = "你好";     //这个是私有变量，外部无法访问
        var dc;
		this.x=arg.x;
		this.y=arg.y;
		this.h=arg.h;
		this.w=arg.w;
		this.r=arg.x+this.w;
		this.b=arg.y+this.h;
		this.Name=arg.Name;
		this.id=arg.id;
		this.Selected=0;
        this.GetButtonInfo = function () {     //this.testFun方法，加上了this，就是公有方法了，外部可以访问。

            alert(arg.x + "," + arg.y+","+arg.w+","+arg.h);

        };
		this.GetLeft = function () {   
           return this.x;

        };
		this.GetTop = function () {   

           return this.y;

        };
		this.GetRight = function () {   

           return this.x+this.w;

        };
		this.GetBottom = function () {   

           return this.y+this.h;

        };
		this.SetDc=function(m_dc){//设置绘图环境
			this.dc=m_dc;
		};
		
		
		this.DrawButton=function(SelectID){
			var offset=3;
			var currentTop=0;
			if(firstMouseMove==0)
			currentTop=offsetTopOfScreen;
			this.dc.textAlign="center";
			this.dc.strokeStyle = '#000000';
			this.dc.setLineDash([0,0]);  //画实现
			this.dc.beginPath();
			this.dc.moveTo(this.GetLeft(),this.GetTop()+currentTop);	 //移动到左上角		
			this.dc.lineTo(this.GetRight(),this.GetTop()+currentTop);  //画到右上角
			this.dc.lineTo(this.GetRight(),this.GetBottom()+currentTop);//画到时右下角
			this.dc.lineTo(this.GetLeft(),this.GetBottom()+currentTop);
			this.dc.lineTo(this.GetLeft(),this.GetTop()+currentTop);
			this.dc.stroke();
			if(SelectID==this.id)//绘制边角小黑点
			{
			this.dc.fillRect(this.x-offset,this.y-offset,offset*2,offset*2); //0
			this.dc.fillRect(this.x+this.w/2-offset,this.y-offset,offset*2,offset*2); //1
			this.dc.fillRect(this.x+this.w-offset,this.y-offset,offset*2,offset*2); //2
			this.dc.fillRect(this.x+this.w-offset,this.y+this.h/2-offset,offset*2,offset*2); //3
			this.dc.fillRect(this.x+this.w-offset,this.y+this.h-offset,offset*2,offset*2); //4
			this.dc.fillRect(this.x+this.w/2-offset,this.y+this.h-offset,offset*2,offset*2); //5
			this.dc.fillRect(this.x-offset,this.y+this.h-offset,offset*2,offset*2); //6
			this.dc.fillRect(this.x-offset,this.y+this.h/2-offset,offset*2,offset*2); //7
			
			
			}
			
			this.dc.fillText(this.Name,this.x+this.w/2,this.y+currentTop+this.h/2,this.w*16);
			//this.dc.fillText(this.Name,x,y);
			this.dc.stroke();
		}
		
		this.Moving=function(point)//对不同边角进行大小调整
		{
			
			//offsetX=obj.x-point.x;
			//offsetY=obj.y-point.y;
			
			if(point.hadSelectElement==1)  //标识选中了一个元素
			{
				
			 //0为左上角的事件
			 if(point.action==0)
			 {
				 var m_w;
				 var m_h;
				 m_w=this.w;
				 m_h=this.h;
				 this.x=point.x;
				 this.y=point.y-offsetTopOfScreen;
				 this.w=this.r-this.x;
				 this.h=this.b-this.y;
				 return 1;
				 
			 }
			
			 //1为上中边的事件
			 if(point.action==1)
			 {
				 var m_w;
				 var m_h;
				 m_w=this.w;
				 m_h=this.h;
				
				 this.y=point.y-offsetTopOfScreen;
				 this.w=this.r-this.x;
				 this.h=this.b-this.y;
				 return 1;
				 
			 }
			 
			 //2为右上角的事件
			 if(point.action==2)
			 {
				 var m_w;
				 var m_h;
				 m_w=this.w;
				 m_h=this.h;
				 this.r=point.x;
				 this.y=point.y-offsetTopOfScreen;
				 this.w=this.r-this.x;
				 this.h=this.b-this.y;
				 return 1;
				 
			 }
			 
			 //3为右中边的事件
			 if(point.action==3)
			 {
				 var m_w;
				 var m_h;
				 m_w=this.w;
				 m_h=this.h;
				 this.r=point.x;
				 
				 this.w=this.r-this.x;
				
				 return 1;
				 
			 }
			 
			  //4为右下角的事件
			 if(point.action==4)
			 {
				 var m_w;
				 var m_h;
				 m_w=this.w;
				 m_h=this.h;
				 this.r=point.x;
				 this.b=point.y-offsetTopOfScreen;
				 this.w=this.r-this.x;
				 this.h=this.b-this.y;
				 return 1;
				 
			 }
			 
			  //5为下中边的事件
			 if(point.action==5)
			 {
				 var m_w;
				 var m_h;
				 m_w=this.w;
				 m_h=this.h;
				
				 this.b=point.y-offsetTopOfScreen;
				 
				 this.h=this.b-this.y;
				 return 1;
				 
			 }
			 
			 //6为左下角的事件
			 if(point.action==6)
			 {
				 var m_w;
				 var m_h;
				 m_w=this.w;
				 m_h=this.h;
				 this.x=point.x;
				 this.b=point.y-offsetTopOfScreen;
				 this.w=this.r-this.x;
				 this.h=this.b-this.y;
				 return 1;
				 
			 }
			 
			  //3为右中边的事件
			 if(point.action==7)
			 {
				 var m_w;
				 var m_h;
				 m_w=this.w;
				 m_h=this.h;
				
				 this.x=point.x;
				 this.w=this.r-this.x;
				
				 return 1;
				 
			 }
			 
			 //这里开始整体移动
			 if(point.action==8)
			 {
				 var m_w;
				 var m_h;
				 m_w=this.w;
				 m_h=this.h;
				 this.x=point.x+point.offsetx;
				 this.y=point.y+point.offsety;
				 this.r=this.x+m_w;
				 this.b=this.y+m_h;
				 return 1;
			 }
			}
			return -1;
			
		}
		/* 光标显示返回值
	      |(0)------- m_hide1(1)---------(2)|
	      |                        			|
	   m_hide0(7)       (8)        		m_hide2(3)
	      |                       			|
		  |                        			|
		  |(6)------- m_hide3(5)---------(4)|
	    */

		this.Hits=function(point){
			
			point.y=point.y-offsetTopOfScreen;
			var offset=4;
			if((this.x-offset)<=point.x&&(this.x+offset)>=point.x&&(this.y-offset)<=point.y&&(this.y+offset)>=point.y)
			{   $("#canvas").css({cursor:"nw-resize" });
				return 0;
			}
			
			if((this.x+this.w/2-offset)<=point.x&&(this.x+this.w/2+offset)>=point.x&&(this.y-offset)<=point.y&&(this.y+offset)>=point.y)
			{
				$("#canvas").css({cursor:"n-resize" });
				return 1;
			}
			if((this.GetRight()-offset)<=point.x&&(this.GetRight()+offset)>=point.x&&(this.y-offset)<=point.y&&(this.y+offset)>=point.y)
			{
				$("#canvas").css({cursor:"ne-resize" });
				return 2;
			}
			
			if((this.GetRight()-offset)<=point.x&&(this.GetRight()+offset)>=point.x&&(this.y+this.h/2-offset)<point.y&&(this.y+this.h/2+offset)>=point.y)
			{
				$("#canvas").css({cursor:"w-resize" });
				return 3;
			}
			
			if((this.GetRight()-offset)<=point.x&&(this.GetRight()+offset)>=point.x&&(this.GetBottom()-offset)<point.y&&(this.GetBottom()+offset)>=point.y)
			{
				$("#canvas").css({cursor:"nw-resize" });
				return 4;
			}
			
			if((this.x+this.w/2-offset)<=point.x&&(this.x+this.w/2+offset)>=point.x&&(this.GetBottom()-offset)<point.y&&(this.GetBottom()+offset)>=point.y)
			{
				$("#canvas").css({cursor:"n-resize" });
				return 5;
			}
			
			if((this.x-offset)<=point.x&&(this.x+offset)>=point.x&&(this.GetBottom()-offset)<point.y&&(this.GetBottom()+offset)>=point.y)
			{
				$("#canvas").css({cursor:"ne-resize" });
				return 6;
			}
			
			if((this.x-offset)<=point.x&&(this.x+offset)>=point.x&&(this.y+this.h/2-offset)<point.y&&(this.y+this.h/2+offset)>=point.y)
			{
				$("#canvas").css({cursor:"w-resize" });
				return 7;
			}
			
			if((this.x+offset)<=point.x&&(this.GetRight()-offset)>=point.x&&(this.y+offset)<=point.y&&(this.GetBottom()-offset)>=point.y)
			{
				
				$("#canvas").css({cursor:"move" });
				
				return 8;
			}
			$("#canvas").css({cursor:"Default" });
			
			return -1;
		}

    };

})(jQuery);	